package cmd

import (
	"fmt"

	"github.com/mcpjungle/mcpjungle/cmd/config"
	"github.com/mcpjungle/mcpjungle/pkg/types"
	"github.com/spf13/cobra"
)

var loginCmd = &cobra.Command{
	Use:   "login [access_token]",
	Args:  cobra.ExactArgs(1),
	Short: "Log in to MCPJungle (Production mode)",
	Long: "Log in to your MCPJungle account with your access token.\n" +
		"This will store the access token in your local configuration file, allowing you to make authenticated requests to the MCPJungle API server.\n" +
		"If you're a standard user, your access token must be generated by an administrator.",
	Annotations: map[string]string{
		"group": string(subCommandGroupAdvanced),
		"order": "6",
	},
	RunE: runLogin,
}

func init() {
	rootCmd.AddCommand(loginCmd)
}

func runLogin(cmd *cobra.Command, args []string) error {
	accessToken := args[0]

	user, err := apiClient.Whoami(accessToken)
	if err != nil {
		return fmt.Errorf("failed to get user: %w", err)
	}
	if user == nil {
		return fmt.Errorf("invalid access token")
	}

	cmd.Println("You are now logged in as " + user.Username)
	if user.Role == string(types.UserRoleAdmin) {
		cmd.Println("You are an administrator of MCPJungle")
	}

	cfg := &config.ClientConfig{
		AccessToken: accessToken,
	}
	if err := config.Save(cfg); err != nil {
		return fmt.Errorf("failed to create client configuration: %w", err)
	}

	cfgPath, err := config.AbsPath()
	if err != nil {
		return fmt.Errorf("failed to get client configuration path: %w", err)
	}
	fmt.Println("Your access token has been saved to", cfgPath)

	return nil
}
